import * as vscode from 'vscode';
import { parse } from '@vue/compiler-dom';

export class VueParser {
  static findInsertPosition(document: vscode.TextDocument, section: 'template' | 'script' | 'style') {
    const ast = parse(document.getText());
    const targetNode = ast.children.find((node: any) => 
      node.tag === section && node.loc.source.trim().startsWith(`<${section}`)
    );

    if (!targetNode) {
      return null;
    }

    return new vscode.Position(
      targetNode.loc.start.line - 1,
      targetNode.loc.start.column
    );
  }

  static async insertCode(editor: vscode.TextEditor, position: vscode.Position, code: string) {
    await editor.edit(editBuilder => {
      editBuilder.insert(position, `\n${code}\n`);
    });

    // 自动格式化插入内容
    await vscode.commands.executeCommand(
      'editor.action.formatSelection', 
      editor.document.uri,
      editor.selection
    );
  }
}
